package com.loren.demo03.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * GlobalEventExecutor.INSTANCE 一个单例的全局事件执行器
     */
    private static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext context) {
        context.channel().writeAndFlush(new TextWebSocketFrame("Channel Active"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, TextWebSocketFrame textWebSocketFrame) {
        // 客户端传输过来的消息
        String content = textWebSocketFrame.text();

        System.out.println("content = " + content);

        for (Channel channel : clients) {
            channel.writeAndFlush(new TextWebSocketFrame("[服务器接收到消息：]" + LocalDateTime.now() + ", 内容: " + content));
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext context) {
        Channel channel = context.channel();
        System.out.println("客户端连接 -> id = " + channel.id().asLongText());
        clients.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext context) {
        Channel channel = context.channel();
        System.out.println("客户端移除 -> id = " + channel.id().asLongText());
        clients.remove(channel);
    }
}
